<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    button{
      position: fixed;
      right: 100px;
      bottom: 100px;
    }
  </style>
</head>

<body>
  <div id="app" style="height: 3000px">
    <button v-backtop="200">回到顶部</button>
  </div>
  <script src="./vue.global.js"></script>
  <script>
    const { createApp } = Vue;
    const app = createApp({
    });
    // 定义全局指令
    app.directive('backtop', {
      mounted(el, binding){
        // 回到顶部按钮 默认隐藏
        el.style.display="none";
        const { value = 200 } = binding
        window.onscroll = () => {
          const sTop = document.documentElement.scrollTop || document.body.scrollTop;
          if (sTop > value) {
            // 显示按钮
            el.style.display="block";
          } else {
            el.style.display="none";
          }
        }
        // 点击按钮回到顶部
        el.onclick = () => {
          window.scrollTo(0, 0)
        }
      },
      beforeUnmount() {
        window.onscroll = null;
      }
    })
    app.mount('#app')
  </script>
</body>

</html>